import { ESGeoExtrudedPolygonUFMS } from '.';
import { bind, Vector } from "earthsdk3";
import { CzmESGeoExtrudedPolygon, ESCesiumViewer } from 'earthsdk3-cesium';


export class CzmESGeoExtrudedPolygonUFMS<T extends ESGeoExtrudedPolygonUFMS = ESGeoExtrudedPolygonUFMS> extends CzmESGeoExtrudedPolygon<T> {
    static override readonly type = this.register<ESGeoExtrudedPolygonUFMS, ESCesiumViewer>("ESCesiumViewer", ESGeoExtrudedPolygonUFMS.type, this);

    constructor(sceneObject: T, czmViewer: ESCesiumViewer) {
        super(sceneObject, czmViewer);
        const viewer = czmViewer.viewer;
        if (!viewer) {
            console.warn(`viewer is undefined!`);
            return;
        }
        {
            sceneObject.absoluteCeilling = true; // 顶部高度为平面
            // 属性同步
            this.ad(bind([sceneObject, 'bottom'], [sceneObject, 'height']));
            this.ad(bind([sceneObject, 'ceilling'], [sceneObject, 'extrudedHeight']));
            this.ad(sceneObject.perPositionHeightChanged.don(() => {
                sceneObject.absoluteBottom = !sceneObject.perPositionHeight;
            }))
            this.ad(sceneObject.absoluteBottomChanged.don(() => {
                sceneObject.perPositionHeight = !sceneObject.absoluteBottom;
            }))
        }
        {
            const update = () => {
                //经纬度 转 Geojson
                const ArrayAdd = (arr: Iterable<unknown> | null | undefined) => {
                    let a = [...new Set(arr)] as [number, number, number][]; //去重加首尾相同
                    if (!Vector.equals(a[0], a[a.length - 1])) a.push(a[0]);
                    return [...a];
                }
                let GeoJsonArr = sceneObject.points;
                if (!GeoJsonArr || GeoJsonArr.length < 3) return;
                let tempPos = [];
                for (let index = 0; index < GeoJsonArr.length; index++) {
                    let el: any = GeoJsonArr[index];
                    tempPos.push([el[0], el[1], el[2] ?? 0]);
                }
                sceneObject.srcGeom = {
                    type: "Polygon",
                    coordinates: [ArrayAdd(tempPos)],
                };
            }
            update();
            this.ad(sceneObject.pointsChanged.don(update));
        }
    }
}